<?php

class  q extends \Xunruicms
{
    public function index()
    {

        $site = require ROOTPATH.'cache/config/site.php';
        $system = require ROOTPATH.'cache/config/system.php';
        $this->template->assign([
            'site' => $site,
            'class' => 'q',
            'meta_title' => '网站迁移工具',
            'http_prefix' => $system['SYS_HTTPS'] ? 'https://' : 'http://',
        ]);
        $this->template->display('q.html');exit;
    }


    public function old()
    {

        $this->template->assign([
            'class' => 'q',
            'meta_title' => '迁移之前的网站-网站迁移工具',
        ]);

        $st = isset($_GET['st']) ? intval($_GET['st']) : 0;
        if ($st == 9) {
            // 设置新域名
            $domain = isset($_POST['domain']) ? $_POST['domain'] : [];
            if (!$domain) {
                $this->_json(0, '域名未填写');
            }
            foreach ($domain as $t) {
                if ($t) {
                    foreach ($t as $a) {
                        if (strpos($a, 'http') !== 0) {
                            $this->_json(0, '域名['.$a.']必须以http或者https开头');
                        }
                    }
                }
            }
            file_put_contents(WEBPATH.'cache/domain.php', dr_array2string($domain));
            $this->_json(1, '即将下一步...', [
                'url' => '/tool/index.php?c=q&m=old'
            ]);
        } elseif ($st == 22) {
            $this->_json(1, '即将下一步...', [
                'url' => '/tool/index.php?c=q&m=old&st=2'
            ]);
        } elseif ($st == 21) {
            $file = WEBPATH.'db.sql';
            if (!is_file($file)) {
                $this->_json(0, '没有找到数据库备份文件：'.WEBPATH.'db.sql');
            }
            $domain = dr_string2array(file_get_contents(WEBPATH.'cache/domain.php'));

            $site = require ROOTPATH.'cache/config/site.php';
            $system = require ROOTPATH.'cache/config/system.php';
            $prefix = $system['SYS_HTTPS'] ? 'https://' : 'http://';

            $rp = [];
            foreach ($site as $i => $t) {
                // 替换主域名
                $site[$i]['SITE_LOGO'] = str_replace($prefix.$t['SITE_DOMAIN'], $domain[$i]['pc'], $t['SITE_LOGO']);
                $site[$i]['SITE_DOMAIN'] = str_replace(['https://', 'http://'], '', $domain[$i]['pc']);
                if ($t['SITE_DOMAIN'] != $site[$i]['SITE_DOMAIN']) {
                    $rp[] = [$t['SITE_DOMAIN'], $site[$i]['SITE_DOMAIN']];
                }
                if ($prefix.$t['SITE_DOMAIN'] != $domain[$i]['pc']) {
                    $rp[] = [$prefix.$t['SITE_DOMAIN'], $domain[$i]['pc']];
                }
                if ($t['SITE_MOBILE']) {
                    $site[$i]['SITE_MOBILE'] = str_replace(['https://', 'http://'], '', $domain[$i]['mobile']);
                    if ($t['SITE_MOBILE'] != $site[$i]['SITE_MOBILE']) {
                        $rp[] = [$t['SITE_MOBILE'], $site[$i]['SITE_MOBILE']];
                    }
                    if ($prefix.$t['SITE_MOBILE'] != $domain[$i]['mobile']) {
                        $rp[] = [$prefix.$t['SITE_MOBILE'], $domain[$i]['mobile']];
                    }
                }
            }
            $this->template->assign([
                'rp' => $rp,
            ]);
            $this->template->display('q_old_21.html');exit;
        } elseif ($st == 1) {
            $file = WEBPATH.'db.sql';
            if (!is_file($file)) {
                $this->_json(0, '没有找到数据库备份文件：'.WEBPATH.'db.sql');
            }

            $domain = dr_string2array(file_get_contents(WEBPATH.'cache/domain.php'));

            $site = require ROOTPATH.'cache/config/site.php';
            $system = require ROOTPATH.'cache/config/system.php';
            $prefix = $system['SYS_HTTPS'] ? 'https://' : 'http://';

            $rp = [];
            foreach ($site as $i => $t) {
                // 替换主域名
                $site[$i]['SITE_LOGO'] = str_replace($prefix.$t['SITE_DOMAIN'], $domain[$i]['pc'], $t['SITE_LOGO']);
                $site[$i]['SITE_DOMAIN'] = str_replace(['https://', 'http://'], '', $domain[$i]['pc']);
                if ($t['SITE_DOMAIN'] != $site[$i]['SITE_DOMAIN']) {
                    $rp[] = [$t['SITE_DOMAIN'], $site[$i]['SITE_DOMAIN']];
                }
                if ($prefix.$t['SITE_DOMAIN'] != $domain[$i]['pc']) {
                    $rp[] = [$prefix.$t['SITE_DOMAIN'], $domain[$i]['pc']];
                }
                if ($t['SITE_MOBILE']) {
                    $site[$i]['SITE_MOBILE'] = str_replace(['https://', 'http://'], '', $domain[$i]['mobile']);
                    if ($t['SITE_MOBILE'] != $site[$i]['SITE_MOBILE']) {
                        $rp[] = [$t['SITE_MOBILE'], $site[$i]['SITE_MOBILE']];
                    }
                    if ($prefix.$t['SITE_MOBILE'] != $domain[$i]['mobile']) {
                        $rp[] = [$prefix.$t['SITE_MOBILE'], $domain[$i]['mobile']];
                    }
                }
            }
            $this->file(WEBPATH.'cache/site.php', '站点配置文件', 32)->to_require($site);

            if ($rp) {
                if (filesize($file) > 1024*1024*10) {
                    $this->_json(1, '备份文件过大，需要手动替换域名...', [
                        'url' => '/tool/index.php?c=q&m=old&st=21'
                    ]);
                }
                $code = $sql = file_get_contents($file);
                foreach ($rp as $t) {
                    // 替换主域名
                    $sql = str_replace($t[0], $t[1], $sql);
                }
                if ($sql == $code) {
                    $this->_json(1, '需要手动替换域名...', [
                        'url' => '/tool/index.php?c=q&m=old&st=21'
                    ]);
                }
                file_put_contents($file, $sql);
            }

            $this->_json(1, '检测到了备份文件，即将下一步...', [
                'url' => '/tool/index.php?c=q&m=old&st=2'
            ]);
        } elseif ($st == 2) {
            $this->template->display('q_old_2.html');
        } elseif ($st == 3) {
            $file = ROOTPATH.'www.zip';
            if (!is_file($file)) {
                $this->_json(0, '没有找到打包文件：'.ROOTPATH.'www.zip');
            }
            $this->_json(1, '检测到了打包文件，即将下一步...', [
                'url' => '/tool/index.php?c=q&m=old&st=4'
            ]);
        } elseif ($st == 4) {
            $domain = dr_string2array(file_get_contents(WEBPATH.'cache/domain.php'));
            $this->template->assign([
                'domain' => $domain[1]['pc'],
            ]);
            $this->template->display('q_old_4.html');
        } else {
            $this->template->display('q_old.html');
        }
        exit;
    }

    public function after()
    {

        if (!is_file(WEBPATH.'cache/domain.php')) {
            exit('文件不存在：'.WEBPATH.'cache/domain.php');
        }

        $st = isset($_GET['st']) ? intval($_GET['st']) : 0;
        if ($st == 1) {

            $data = $_POST['data'];
            if (empty($data['db_host'])) {
                $this->_json(0, '数据库地址不能为空');
            } elseif (empty($data['db_user'])) {
                $this->_json(0, '数据库账号不能为空');
            } elseif (empty($data['db_name'])) {
                $this->_json(0, '数据库名称不能为空');
            } elseif (empty($data['db_pass'])) {
                $this->_json(0, '数据库密码不能为空');
            } elseif (is_numeric($data['db_name'])) {
                $this->_json(0, '数据库名称不能是数字');
            } elseif (strpos($data['db_name'], '.') !== false) {
                $this->_json(0, '数据库名称不能存在.号');
            }

            $mysqli = function_exists('mysqli_init') ? mysqli_init() : 0;
            if (!$mysqli) {
                $this->_json(0, '您的PHP环境必须启用Mysqli扩展');
            } elseif (!mysqli_real_connect($mysqli, $data['db_host'], $data['db_user'], $data['db_pass'])) {
                $this->_json(0, '['.mysqli_connect_errno().'] - 无法连接到数据库服务器（'.$data['db_host'].'），请检查用户名（'.$data['db_user'].'）和密码（'.$data['db_pass'].'）是否正确');
            } elseif (!mysqli_select_db($mysqli, $data['db_name'])) {
                if (!mysqli_query($mysqli, 'CREATE DATABASE '.$data['db_name'])) {
                    $this->_json(0, '指定的数据库（'.$data['db_name'].'）不存在，系统尝试创建失败，请通过其他方式建立数据库');
                }
            }

            $db = [];
            $db['default'] = [];
            require ROOTPATH.'config/database.php';

            if (!isset($db['default']['DBPrefix'])) {
                $this->_json(0, '未抓到数据库表前缀');
            }

            // 存储mysql
            $database = '<?php

/**
 * 数据库配置文件
 */

$db[\'default\']	= [
    \'hostname\'	=> \''.$data['db_host'].'\',
    \'username\'	=> \''.$data['db_user'].'\',
    \'password\'	=> \''.$data['db_pass'].'\',
    \'database\'	=> \''.$data['db_name'].'\',
    \'DBPrefix\'	=> \''.dr_safe_filename($db['default']['DBPrefix']).'\',
];';
            $size = file_put_contents(ROOTPATH.'config/database.php', $database);
            if (!$size || $size < 10) {
                $this->_json(0, '数据库配置文件创建失败，config目录无法写入');
            }
            $this->_json(1, '数据库配置成功，即将下一步...', [
                'url' => '/tool/index.php?c=q&m=after&st=2'
            ]);
        } elseif ($st == 3) {
            $db = [];
            $mysqli = function_exists('mysqli_init') ? mysqli_init() : 0;
            require ROOTPATH.'config/database.php';

            if (!$mysqli) {
                $this->_json(0, 'PHP环境必须启用Mysqli扩展');
            } elseif (!mysqli_real_connect($mysqli, $db['default']['hostname'], $db['default']['username'], $db['default']['password'])) {
                $this->_json(0, '['.mysqli_connect_errno().'] - 无法连接到数据库服务器（'.$db['default']['hostname'].'），
                请检查用户名（'.$db['default']['username'].'）和密码（'.$db['default']['password'].'）是否正确');
            } elseif (!mysqli_select_db($mysqli, $db['default']['database'])) {
                $this->_json(0, '指定的数据库（'.$db['default']['database'].'）不存在');
            }

            // 判断是否安装过
            $result = mysqli_query($mysqli, 'SHOW FULL COLUMNS FROM `'.$db['default']['DBPrefix'].'cron`');
            if (!$result) {
                $this->_json(0, '数据没有成功导入');
            }


            $site = require WEBPATH.'cache/site.php';
            $this->file(ROOTPATH.'cache/config/site.php', '站点配置文件', 32)->to_require($site);

            // 清空
            dr_dir_delete(ROOTPATH.'cache/attach');
            dr_mkdirs(ROOTPATH.'cache/attach');

            $this->_json(1, '数据库配置成功，即将完成...', [
                'url' => '/tool/index.php?c=q&m=after&st=4'
            ]);
        } elseif ($st == 4) {
            $admin = FC_NOW_URL;
            $files = dr_file_map(ROOTPATH);
            foreach ($files as $file) {
                if (strpos($file, '.php') !== false && $file != 'index.php') {
                    $code = file_get_contents(ROOTPATH.$file);
                    if (strpos($code, "define('IS_ADMIN', TRUE)") !== false) {
                        $admin = '/'.$file;
                    }
                }
            }
            $this->template->assign([
                'admin' => $admin,
                'class' => 'q',
                'meta_title' => '迁移后的网站-网站迁移工具',
            ]);
            $this->template->display('q_after_4.html');
        } elseif ($st == 2) {
            $this->template->assign([
                'class' => 'q',
                'meta_title' => '迁移后的网站-网站迁移工具',
            ]);
            $this->template->display('q_after_2.html');
        } else {
            $domain = dr_string2array(file_get_contents(WEBPATH.'cache/domain.php'));
            $this->template->assign([
                'domain' => $domain[1]['pc'],
                'class' => 'q',
                'meta_title' => '迁移后的网站-网站迁移工具',
            ]);
            $this->template->display('q_after.html');
        }

        exit;
    }
}
